package com.lcxw.hxzbapi.scheduleTask;

import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbapi.entity.pojo.CubeDrawRange;
import com.lcxw.hxzbapi.entity.pojo.CubeDrawRecord;
import com.lcxw.hxzbapi.service.CubeDrawRecordService;
import com.lcxw.hxzbapi.service.YwpdMemberService;
import com.lcxw.hxzbcommon.common.RedisUtils;
import com.lcxw.hxzbcommon.common.RoomUtils;
import com.lcxw.hxzbcommon.common.StringUtil;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class CubeDrawRangeScheduled {

    @Resource
    CubeDrawRecordService cubeDrawRecordService;

    @Resource
    YwpdMemberService memberService;

    @Resource
    RedisUtils redisUtils;

    @Scheduled(cron = "0 * * * * ? ")
    public void countCubeDrawRange() {

        String drawRangeRedisKey = RoomUtils.getDrawRangeRedisKey();

        HashMap<Long, Integer> countMap = new HashMap<>();

        List<Long> userIds = cubeDrawRecordService.selectTodayUser();
        for (Long userId : userIds
        ) {
            List<CubeDrawRecord> cubeDrawRecords = cubeDrawRecordService.selectTodayListUser(userId);
            int total = 0;
            for (CubeDrawRecord cubeDrawRecord : cubeDrawRecords
            ) {
                Integer giftId = cubeDrawRecord.getGiftId();
                Integer giftNum = cubeDrawRecord.getGiftNum();
                int oneGiftCount = cubeDrawRecordService.getOneGiftCount(giftNum, giftId) * 10;
                total += oneGiftCount;
            }
            countMap.put(userId, total);
        }

        Map<?, Integer> countResult = StringUtil.mapSortByValue(countMap);
        redisUtils.list_delete(drawRangeRedisKey);
        for (Object userId : countResult.keySet()
        ) {
            CubeDrawRange cubeDrawRange = new CubeDrawRange();
            cubeDrawRange.setUserId((Long) userId);
            cubeDrawRange.setImgUrl(memberService.selectImgUrlByuserId((Long) userId));
            cubeDrawRange.setNickName(memberService.selectNickNameByUserId((Long) userId));
            cubeDrawRange.setCubeDrawTotal(countResult.get(userId));
            redisUtils
                .list_rightPush(drawRangeRedisKey, JSONObject.toJSONString(cubeDrawRange));
        }
    }

}
